/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.anorien.dmo.gui.optimization;

import eu.anorien.dmo.Server;
import eu.anorien.dmo.proxy.ServerBusyException;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class ServerPool {

    private static final Logger logger = Logger.getLogger(ServerPool.class);
    private static ServerPool instance;
    private ArrayList<Server> servers;
    private final Object lock = new Object();
    private int nRunning = 0;

    public static void init(ArrayList<Server> servers) {
        instance = new ServerPool(servers);
    }

    private ServerPool(ArrayList<Server> servers) {
        this.servers = servers;
    }

    public static ServerPool getInstance() {
        return instance;
    }

    public ArrayList<Server> getServers() {
        return servers;
    }

    public double runFunction(String name, String parameters) {
        logger.info(nRunning + " servers are currently running");
        synchronized (lock) {
            nRunning++;
        }
        try {
            double rslt;
            outter:
            while (true) {
                for (Server server : servers) {
                    try {
                        rslt = server.getProxy().runFunction(server.getPassword(), name, parameters);
                        break outter;
                    } catch (ServerBusyException ex) {
                        logger.info("Server " + server + " is busy");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }
            return rslt;
        } finally {
            synchronized (lock) {
                nRunning--;
            }
        }
    }
}
